﻿using System;
using System.Diagnostics;
using PostSharp.Aspects;

namespace Theoreme.Teaching.AOP.Sample01
{
    // @Section(IncrementPerformanceCounterAttribute)

    /// <summary>
    /// Aspect that, when applied on a method, feed a performance counter
    /// with the number of times a method has been invoked.
    /// </summary>
    [Serializable]
    public sealed class InstrumentExceptionRateAttribute : PerformanceCounterAttribute
    {
        public InstrumentExceptionRateAttribute(string categoryName, string counterName)
            : base( categoryName, counterName, PerformanceCounterType.AverageCount64, PerformanceCounterType.AverageBase )
        {
        }

        /// <summary>
        /// Method invoked when a method exits with an exception.
        /// </summary>
        /// <param name="args">Unused.</param>
        public override void OnException( MethodExecutionArgs args )
        {
            if ( this.PerformanceCounter != null )
            {
                this.PerformanceCounter.Increment();
            }
        }

        public override void OnExit(MethodExecutionArgs args)
        {
            if ( this.PerformanceCounter != null )
            {
                this.BasePerformanceCounter.Increment();
            }
        }
    }

    // @Section()
}